package com.ngovanhau.justsort.model;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.modifier.DelayModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.util.HorizontalAlign;
import org.anddev.andengine.util.modifier.IModifier;
import org.anddev.andengine.entity.IEntity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;

import com.ngovanhau.justsort.MainGameActivity;
import com.ngovanhau.justsort.MySprite;
import com.ngovanhau.justsort.control.ValueControl;
import com.ngovanhau.justsort.item.config.MyConfig;

public class MyText extends MySprite {

	Font font;
	BitmapTextureAtlas font_BTA;

	public ChangeableText timer;
	ChangeableText move;
	Text level;

	float size_font = 42;

	int time = 0;

	boolean isStop = false;

	public void onLoadResources(Engine engine, Context context) {
		this.engine = engine;
		this.context = context;
		this.mainGame = (MainGameActivity) context;
		this.font_BTA = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.font = new Font(font_BTA, Typeface.createFromAsset(
				context.getAssets(), "font/TCCEB.TTF"), size_font
				* MyConfig.RACE_HEIGHT, true, Color.WHITE);
		engine.getTextureManager().loadTexture(font_BTA);
		engine.getFontManager().loadFont(font);
	}

	public void onLoadScene(Scene scene) {
		this.scene = scene;

		int y_top = (int) ((MyConfig.HEIGHT_TOP - size_font - 20 * MyConfig.RACE_WIDTH)
				* MyConfig.RACE_HEIGHT / 2);
		level = new Text(MyConfig.SCREENWIDTH - 170 * MyConfig.RACE_WIDTH,
				y_top, font, "LV" + LevelSetting.currentLevel + ": "
						+ LevelSetting.rowLevel + "x"
						+ LevelSetting.columnLevel, HorizontalAlign.RIGHT);
		scene.attachChild(level);
		level.setZIndex(99);
		scene.sortChildren();
		level.setColor(0f, 0.83f, 0.02f);

		int y_bottom = (int) (MyConfig.SCREENHEIGHT - 5 * MyConfig.RACE_WIDTH - (MyConfig.HEIGHT_BOTTOM + size_font)
				* MyConfig.RACE_HEIGHT / 2);

		timer = new ChangeableText(MyConfig.SCREENWIDTH - 100
				* MyConfig.RACE_WIDTH, y_bottom, font,
				LevelSetting.TimeOutCurrentLevel + "s", 4);
		scene.attachChild(timer);
		setLocationTime();

		move = new ChangeableText(
				(MyConfig.SCREENWIDTH - 100 * MyConfig.RACE_WIDTH) / 2,
				y_bottom, font, "0", 100);
		scene.attachChild(move);
		setLocationMove();
		move.setVisible(false);

		// bonus = new ChangeableText(
		// (MyConfig.SCREENWIDTH - 100 * MyConfig.RACE_WIDTH) / 2,
		// y_bottom, font, "+0", 100);
		// scene.attachChild(bonus);
		// setLocationMove();
		// bonus.setVisible(false);
	}

	public void setLocationTime() {
		timer.setPosition(
				MyConfig.SCREENWIDTH - MyConfig.X_START - timer.getWidth(),
				timer.getY());
	}

	public void setLocationMove() {
		move.setPosition((MyConfig.SCREENWIDTH - move.getWidth()) / 2,
				move.getY());
	}

	public void start() {
		time = 0;
		(new Thread(new Runnable() {
			@Override
			public void run() {
				while (!ValueControl.isCompletedLevel && !isStop) {
					try {
						if (ValueControl.isTouchNumber && (!ValueControl.isCompletedLevel)) {
							Thread.sleep(1000);
							addTime(1);
							if (time >= LevelSetting.TimeOutCurrentLevel) {
								break;
							}
							// update timer;
							updateTime(time);
							setLocationTime();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if ((time >= LevelSetting.timeMinLevel
						&& !ValueControl.isCompletedLevel && !isStop)
						|| time >= LevelSetting.TimeOutCurrentLevel) {
					mainGame.makeTimeout();
				}
			}
		})).start();
	}

	public void setMove(final int moveTime) {
		engine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				move.setText("" + moveTime);
				setLocationMove();
			}
		});
	}

	public void startMove() {
		engine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				move.setText("" + LevelSetting.TimeOutMoveCurrentLevel);
				move.setVisible(true);
			}
		});
	}

	public void stopMove() {

		engine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				move.setVisible(false);
			}
		});
	}

	public void updateTime(final int timenow) {
		engine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				timer.setText((LevelSetting.TimeOutCurrentLevel - timenow)
						+ "s");
			}
		});
	}

	public void addTime(int i) {
		synchronized (mainGame) {
			if (ValueControl.isTouchNumber) {
				time += i;
				updateTime(time);
			}
		}
	}

	public void subTime(final int i) {
		(new Thread(new Runnable() {

			@Override
			public void run() {
				ValueControl.isTouchNumber = false;
				for (int j = 1; j <= i; j++) {
					time -= 1;
					updateTime(time);
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				mainGame.bonus_items.add(
						(int) (mainGame.text.timer.getX() - 20),
						(int) (mainGame.text.timer.getY() - 20), "+" + i);
				ValueControl.isTouchNumber = true;
			}
		})).start();

	}

	public void stop() {
		isStop = true;
	}

	public int getTime() {
		synchronized (this) {
			return time;
		}
	}

	// -------------------------------------------------------------------------
	/**
	 * Hiện thị text thông báo level hiện tại
	 */
	public void showTextLevel() {
		String textLevel = LevelSetting.rowLevel + "x"
				+ LevelSetting.columnLevel;
		float sizefont = 200;

		float pX = MyConfig.getCenterX() - font.getStringWidth(textLevel) / 2;
		float pY = MyConfig.getCenterY() - sizefont / 2;

		final ChangeableText levelNext = new ChangeableText(pX, pY, font,
				textLevel);
		levelNext.setScale(0f);
		levelNext.setColor(0.85f, 0.4f, 0.0f);
		scene.attachChild(levelNext);

		ScaleModifier mScaleModifier_in = new ScaleModifier(0.5f, 0f, 4f);
		RotationModifier mRotationModifier_in = new RotationModifier(0.5f, 0,
				360);
		ParallelEntityModifier mParallelEntityModifier_in = new ParallelEntityModifier(
				mScaleModifier_in, mRotationModifier_in);

		DelayModifier mDelayModifier = new DelayModifier(1.5f);

		ScaleModifier mScaleModifier_out = new ScaleModifier(0.5f, 4f, 0f);
		RotationModifier mRotationModifier_out = new RotationModifier(0.5f, 0,
				-360);
		ParallelEntityModifier mParallelEntityModifier_out = new ParallelEntityModifier(
				mScaleModifier_out, mRotationModifier_out);

		SequenceEntityModifier mSequenceEntityModifier = new SequenceEntityModifier(
				new SequenceEntityModifier.ISubSequenceShapeModifierListener() {
					@Override
					public void onSubSequenceStarted(
							IModifier<IEntity> pModifier, IEntity pItem,
							int pIndex) {
					}

					@Override
					public void onSubSequenceFinished(
							IModifier<IEntity> pModifier, IEntity pItem,
							int pIndex) {
						if (pIndex == 2) {
							removeChangeableText(levelNext);
							ValueControl.isTouchNumber = true;
							start();
						}
					}
				}, mParallelEntityModifier_in, mDelayModifier,
				mParallelEntityModifier_out);
		levelNext.registerEntityModifier(mSequenceEntityModifier);
	}

	public void removeChangeableText(final ChangeableText textLevelStart) {
		engine.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				scene.detachChild(textLevelStart);
			}
		});
	}
}
